<template>
  <div class="container" v-show="showContainer">
    <h2 class="animate__animated animate__fadeInDown">登录</h2>
    <form @submit.prevent="handleLogin" class="animate__animated animate__fadeInUp">
      <div class="form-group">
        <label for="username">用户名</label>
        <input type="text" id="username" v-model="username" required class="form-control" />
      </div>
      <div class="form-group">
        <label for="password">密码</label>
        <input type="password" id="password" v-model="password" required class="form-control" />
      </div>
      <button type="submit" class="btn btn-primary">登录</button>
    </form>
    <p class="text-center">
      没有账号？<a href="#" @click="showRegister" @click.prevent>去注册</a>
    </p>
  </div>
</template>

<script setup>
import { ref, defineEmits } from 'vue';
import { useAuthStore } from '@/stores/auth';

const showContainer = ref(true);
const username = ref('');
const password = ref('');
const authStore = useAuthStore();
const emit = defineEmits(['register']); // 明确声明 emit

const handleLogin = () => {
  const users = JSON.parse(localStorage.getItem('users')) || [];

  const user = users.find(
    (u) => u.username === username.value && u.password === password.value
  );

  if (user) {
    authStore.login({ name: user.username }); // 确保 user 对象包含 name 属性
  } else {
    alert('用户名或密码错误');
  }
};

const showRegister = () => {
  // 通知父组件切换到注册页面
  showContainer.value = false;
  emit('register'); // 发出 register 事件通知父组件
};
</script>

<style scoped>
.container {
  max-width: 350px;
  margin: 20px auto;
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-control {
  width: calc(100% - 50px);
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.btn {
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn-primary {
  background-color: #007bff;
  color: white;
  margin-top: 10px;
  width:calc(100% - 30px);
}

.text-center {
  text-align: center;
  margin-top: 15px;
}

a {
  color: #007bff;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}
</style>